package com.bawei.module_live

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.mvi.base.BaseMVIFragment
import com.bawei.module_live.adapter.VideoPagerAdapter
import com.bawei.module_live.intent.LiveIntent
import com.bawei.module_live.layout.VideoLayoutManager
import com.bawei.module_live.manager.VideoPlayerManager
import com.bawei.module_live.player.ExoPlayerManager
import com.bawei.module_live.state.LiveState
import com.bawei.module_live.version1.VideoEntity
import com.bawei.module_live.version1.VideoEntityItem
import com.bawei.module_live.viewmodel.LiveViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch

class LiveFragment : BaseMVIFragment() {

    private lateinit var binding: View
    private lateinit var rvVideos: RecyclerView
    private lateinit var progressBar: ProgressBar

    private lateinit var viewModel: LiveViewModel
    private val videoAdapter: VideoPagerAdapter by lazy { VideoPagerAdapter() }
    private val videoPlayerManager: VideoPlayerManager by lazy { VideoPlayerManager() }
    private val exoPlayerManager: ExoPlayerManager by lazy {
        ExoPlayerManager(requireContext())
    }
    private val handler = Handler(Looper.getMainLooper())
    private var playRetryCount = 0
    private val MAX_RETRY = 5
    private val RETRY_DELAY = 100L

    override fun generateViewModel() {
        viewModel = ViewModelProvider(this)[LiveViewModel::class.java]

        // viewModel 初始化完成后，触发数据加载
        lifecycleScope.launch {
            // 先使用测试数据确保视频播放功能正常
            testVideoPlayback()

            // 然后发起网络请求获取真实数据
            viewModel.intents.send(LiveIntent.GetVideo(page = 1, pageSize = 50))
        }
    }

    override fun lazyLoad() {
        // 懒加载逻辑已经在 generateViewModel 中处理
        // 这里不需要重复处理，避免在 viewModel 未初始化时调用
        Log.d("LiveFragment", "lazyLoad 被调用，但数据加载已在 generateViewModel 中处理")
    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = inflater.inflate(R.layout.fragment_live, container, false)
        rvVideos = binding.findViewById(R.id.rv_videos)
        progressBar = binding.findViewById(R.id.progress_bar)
        return binding
    }

    override fun handleState() {
        // 处理状态变化
        lifecycleScope.launch {
            viewModel.liveFlow_.collect { state ->
                when (state) {
                    is LiveState.Init -> {
                        // 初始状态，不做处理
                        Log.d("LiveFragment", "handleState: 初始状态")
                    }

                    is LiveState.Loading -> {
                        // 显示加载状态
                        showLoading(true)
                        Log.d("LiveFragment", "handleState: 正在加载")
                    }

                    is LiveState.Success -> {
                        // 数据加载成功
                        showLoading(false)
                        Log.d("LiveFragment", "handleState: 加载成功,共${state.data.size}条数据")
                        updateUI(state.data)
                    }

                    is LiveState.Empty -> {
                        // 数据为空
                        showLoading(false)
                        Log.d("LiveFragment", "handleState: 暂无数据")
                        showEmptyState()
                    }

                    is LiveState.Failed -> {
                        // 加载失败
                        showLoading(false)
                        Log.d("LiveFragment", "handleState: 加载失败: ${state.message}")
                        showErrorState(state.message)
                    }

                    is LiveState.GoodsListSuccess -> {
                        // 商品列表成功，直播页不用处理
                    }

                    is LiveState.GoodsListFailed -> {
                        // 商品列表失败，直播页不用处理
                    }
                }
            }
        }
    }

    override fun initView() {
        super.initView()

        //环信登录
        val account = MMKV.defaultMMKV().decodeString("account")
        val password = MMKV.defaultMMKV().decodeString("password")
        if (account==null){
            ARouter.getInstance().build("/module_mine/LoginActivity").navigation()
        }

        // 测试编译是否成功
        testCompilation()

        // 初始化 RecyclerView
        setupRecyclerView()

        // 设置视频播放管理器
        setupVideoPlayerManager()

        // 设置适配器点击事件
        setupAdapterClickListener()

        // 监听首屏 ViewHolder attach 后再自动播放
        rvVideos.addOnChildAttachStateChangeListener(object :
            RecyclerView.OnChildAttachStateChangeListener {
            override fun onChildViewAttachedToWindow(view: View) {
                val holder = rvVideos.getChildViewHolder(view)
                if (holder is com.bawei.module_live.adapter.VideoPagerAdapter.VideoViewHolder && holder.adapterPosition == 0) {
                    // 延迟 200ms 再自动播放
                    rvVideos.postDelayed({
                        videoPlayerManager.playVideoAtPosition(0)
                    }, 200)
                }
            }

            override fun onChildViewDetachedFromWindow(view: View) {}
        })
    }

    private fun setupRecyclerView() {
        rvVideos.apply {
            layoutManager = VideoLayoutManager(requireContext())
            adapter = videoAdapter
            // 设置预加载数量
            setItemViewCacheSize(3)
            // 设置固定高度，确保每个项目都是全屏
            setHasFixedSize(true)
        }
        Log.d("LiveFragment", "RecyclerView 设置完成")
    }

    private fun setupVideoPlayerManager() {
        videoPlayerManager.setRecyclerView(rvVideos, exoPlayerManager)

        // 设置视频播放监听
        videoPlayerManager.setOnVideoPlayListener { video, position ->
            Log.d("LiveFragment", "开始播放视频: ${video.title} at position: $position")
            //Toast.makeText(requireContext(), "播放: ${video.title}", Toast.LENGTH_SHORT).show()
        }
        // 设置视频暂停监听
        videoPlayerManager.setOnVideoPauseListener { video, position ->
            Log.d("LiveFragment", "暂停播放视频: ${video.title} at position: $position")
        }

        Log.d("LiveFragment", "视频播放管理器设置完成")
    }

    private fun setupAdapterClickListener() {
        videoAdapter.setOnVideoClickListener { video, position ->
            Log.d("LiveFragment", "点击视频: ${video.title} at position: $position")
            // 这里可以添加视频点击逻辑，比如跳转到详情页
            Toast.makeText(requireContext(), "点击了: ${video.title}", Toast.LENGTH_SHORT).show()
            ARouter.getInstance().build("/module_live/LiveDetailActivity")
                .withString("videoPath", video.videopath)
                .withString("videoTitle", video.title)
                .withString("videoName", video.name)
                .withString("videoAvatar", video.avatar_url) // 新增头像url传递
                .withString("anchorId", video.userid) // 主播id传递，类型为String
                .withLong("videoProgress", exoPlayerManager.getCurrentPosition().toLong())
                .navigation()

        }
    }

    /**
     * 更新UI显示数据
     */
    private fun updateUI(data: VideoEntity) {
        try {
            if (data.isNotEmpty()) {
                Log.d("LiveFragment", "开始更新UI，数据条数: ${data.size}")

                // 打印前几个视频的信息用于调试
                data.take(3).forEachIndexed { index, video ->
                    Log.d("LiveFragment", "视频$index: ${video.title}, 路径: ${video.videopath}")
                }

                videoAdapter.updateData(data)
                Log.d("LiveFragment", "更新UI成功，数据条数: ${data.size}")

                // 数据加载完成后，自动播放第一个视频
                lifecycleScope.launch {
                    kotlinx.coroutines.delay(1000) // 等待UI渲染完成
                    playFirstVideo()
                }
            } else {
                showEmptyState()
            }
        } catch (e: Exception) {
            Log.e("LiveFragment", "updateUI error: ${e.message}")
            e.printStackTrace()
            showErrorState("更新UI失败")
        }
    }

    /**
     * 播放第一个视频
     */
    private fun playFirstVideo() {
        try {
            Log.d("LiveFragment", "准备播放第一个视频")
            val firstVideo = videoAdapter.getVideoAtPosition(0)
            if (firstVideo != null) {
                Log.d("LiveFragment", "第一个视频: ${firstVideo.title}")
                Log.d("LiveFragment", "第一个视频路径: ${firstVideo.videopath}")

                val viewHolder = rvVideos.findViewHolderForAdapterPosition(0)
                if (viewHolder is VideoPagerAdapter.VideoViewHolder) {
                    playRetryCount = 0 // reset retry count

                    val playerView = viewHolder.getPlayerView()
                    val videoCover = viewHolder.getVideoCover()

                    // 设置播放器视图
                    exoPlayerManager.setPlayerView(playerView)

                    // 隐藏视频封面
                    videoCover.visibility = View.GONE

                    // 播放视频
                    exoPlayerManager.playVideo(firstVideo, 0)

                    Log.d("LiveFragment", "自动播放第一个视频: ${firstVideo.title}")
                } else {
                    Log.w("LiveFragment", "未找到第一个视频的 ViewHolder")
                    // ViewHolder 还没渲染，延迟重试
                    if (playRetryCount < MAX_RETRY) {
                        playRetryCount++
                        handler.postDelayed({ videoPlayerManager.playCurrentVideo() }, RETRY_DELAY)
                    } else {
                        playRetryCount = 0
                    }
                }
            } else {
                Log.w("LiveFragment", "未找到第一个视频数据")
            }
        } catch (e: Exception) {
            Log.e("LiveFragment", "playFirstVideo error: ${e.message}")
            e.printStackTrace()
        }
    }

    /**
     * 显示/隐藏加载状态
     */
    private fun showLoading(show: Boolean) {
        try {
            progressBar.visibility = if (show) View.VISIBLE else View.GONE
        } catch (e: Exception) {
            Log.e("LiveFragment", "showLoading error: ${e.message}")
        }
    }

    /**
     * 显示空状态
     */
    private fun showEmptyState() {
        try {
            Toast.makeText(requireContext(), "暂无视频数据", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Log.e("LiveFragment", "showEmptyState error: ${e.message}")
        }
    }

    /**
     * 显示错误状态
     */
    private fun showErrorState(message: String) {
        try {
            Toast.makeText(requireContext(), "加载失败: $message", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Log.e("LiveFragment", "showErrorState error: ${e.message}")
        }
    }

    /**
     * 测试视频播放功能
     */
    private fun testVideoPlayback() {
        try {
            Log.d("LiveFragment", "开始测试视频播放功能")

            // 创建测试视频数据
            val testVideo = VideoEntityItem(
                avatar_url = "",
                channelid = "test",
                commentnum = 100,
                ctime = "",
                description = "测试视频描述",
                group_id = "test",
                id = 1,
                image_url = "",
                item_id = "test",
                labelIds = "",
                name = "测试用户",
                playnum = 1000,
                preview_url = "",
                publish_time = "",
                title = "测试视频标题",
                userid = "test",
                verifycode = "",
                videomainimag = "",
                videopath = "" // 空路径，会使用测试视频
            )

            // 创建测试数据列表
            val testData = VideoEntity().apply {
                add(testVideo)
                add(testVideo.copy(id = 2, title = "测试视频2"))
                add(testVideo.copy(id = 3, title = "测试视频3"))
            }

            // 更新适配器数据
            videoAdapter.updateData(testData)

            // 延迟播放第一个视频
            lifecycleScope.launch {
                kotlinx.coroutines.delay(1000)
                playFirstVideo()
            }

            Log.d("LiveFragment", "测试视频播放功能设置完成")

        } catch (e: Exception) {
            Log.e("LiveFragment", "测试视频播放功能失败: ${e.message}")
            e.printStackTrace()
        }
    }

    /**
     * 测试编译是否成功
     */
    private fun testCompilation() {
        try {
            Log.d("LiveFragment", "编译测试成功")
            Log.d("LiveFragment", "ViewModel: $viewModel")
            Log.d("LiveFragment", "VideoAdapter: $videoAdapter")
            Log.d("LiveFragment", "VideoPlayerManager: $videoPlayerManager")
            Log.d("LiveFragment", "ExoPlayerManager: $exoPlayerManager")
        } catch (e: Exception) {
            Log.e("LiveFragment", "编译测试失败: ${e.message}")
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 彻底释放视频播放资源，防止内存泄漏和后台播放
        videoPlayerManager.release()
    }

    override fun onPause() {
        super.onPause()
        // 暂停视频播放，防止切换Fragment时声音继续播放
        videoPlayerManager.pause()
    }
}